﻿@{
    ViewBag.Title = "";
    var id = Model != null ? Model.ID : 0;
    var insuranceCompanyName = string.Empty;
    if (Model != null && Model.InsuranceCompanyID.HasValue)
    {
        insuranceCompanyName = Model.InsuranceCompany.CompanyName;
    }
}
@using ZBJF.Warranty.BLL
@using ZBJF.Warranty.WebProvider
@model ZBJF.Warranty.Model.SellerInsuranceProducts
@using EnumHelper = ZBJF.Warranty.Common.Common.EnumHelper
@section Header{
    @Styles.Render("~/Content/chosen")
}
<link href="~/Scripts/Umditor/themes/default/css/umeditor.css" type="text/css" rel="stylesheet">
<script type="text/javascript" charset="gbk" src="~/Scripts/Umditor/umeditor.min.js"></script>
<script type="text/javascript" charset="gbk" src="~/Scripts/Umditor/umeditor.config.js"></script>
<script src="~/Scripts/Umditor/lang/zh-cn/zh-cn.js"></script>
<ul class="nav nav-tabs">
    <li class="active"><a target="_blank" href="JavaScript:void(0)">@Html.Label(Model == null ? "新建商户保险产品" : "编辑商户保险产品")</a></li>
</ul>
<style>
    #img li {
        display: inline-block;
    }
</style>
<h4>商户保险产品基本信息</h4>
@using (Html.BeginForm("SaveSellerInsuranceProducts", "SellerInsuranceProducts", FormMethod.Post, new { id = "mvcForm", name = "mvcForm", @class = "form-horizontal", enctype = "multipart/form-data" }))
{
    @Html.HiddenFor(m => m.Intro)
    @Html.HiddenFor(m => m.ID)
    @Html.Hidden("SellerId", Request["SellerId"])
    <table class="table table-bordered">
        <tr>
            <th>商户保险产品名称：</th>
            <td>
                @Html.TextBoxFor(m => m.ProductName, new { maxlength = 20, @class = "input-small", @style = "width:150px;", validate = "{required:true,messages:{required:'请输入保险卡产品！'}}" })
            </td>
            <th>承保公司：</th>
            <td>
                @Html.TextBox("InsuranceCompanyName", insuranceCompanyName, new { validate = "{required:true,messages:{required:'请选择承保公司'}}", @readonly = "readonly", @class = "select-icon w-p95", onclick = "showLayerOpen('选择承保公司','/PubModelDialog/InsuranceCompanySelector?chkStyle=radio&textid=InsuranceCompanyName&hiddenId=InsuranceCompanyID','320px','60%')" })
                @Html.HiddenFor(m => m.InsuranceCompanyID)
            </td>
            <th>投放量：</th>
            <td>
                @Html.TextBoxFor(m => m.MaxSalesQty, new { Value = Model != null && Model.ID > 0 ? Model.MaxSalesQty : 9999, maxlength = 20, @class = "input-small", onkeyup = "onlyInputInt(this)", validate = "{required:true,messages:{required:'请输入投放量！'}}" })<span> 份</span>
            </td>
            <th>每身份证限购：</th>
            <td>
                @Html.TextBoxFor(m => m.IdentityCardLimitQty, new { Value = Model != null && Model.ID > 0 ? Model.IdentityCardLimitQty : 20, maxlength = 20, @class = "input-small", onkeyup = "onlyInputInt(this)", validate = "{required:true,messages:{required:'请输入身份证限购数！'}}" })<span> 份</span>
            </td>
        </tr>
        <tr>
            <th>保险公司零售价：</th>
            <td>
                @Html.TextBoxFor(m => m.SaleRetailPrice, new { Value = Model != null && Model.ID > 0 ? Model.SaleRetailPrice.ToString() : "", maxlength = 20, @class = "input-small", onkeyup = "onlyInputDecimal(this)", validate = "{required:true,messages:{required:'请输入保险公司零售价！'}}" })<span> 元</span>
            </td>
            <th>经销商零售价：</th>
            <td>
                @Html.TextBoxFor(m => m.InsuranceCompanyRetailPrice, new { Value = Model != null && Model.ID > 0 ? Model.InsuranceCompanyRetailPrice.ToString() : "", maxlength = 20, @class = "input-small", onkeyup = "onlyInputDecimal(this)", validate = "{required:true,messages:{required:'请输入经销商零售价！'}}" })<span> 元</span>
            </td>
            <th>中保销售价：</th>
            <td>
                @Html.TextBoxFor(m => m.ZBJFSalePrice, new { Value = Model != null && Model.ID > 0 ? Model.ZBJFSalePrice.ToString() : "", maxlength = 20, @class = "input-small", onkeyup = "onlyInputDecimal(this)", validate = "{required:true,messages:{required:'请输入中保销售价！'}}" })<span> 元</span>
            </td>
            <th></th>
            <td></td>
        </tr>
    </table>
    <div id="myTabContent" class="tab-content">
        <div class="tab-pane fade in active" id="li2">
            <input id="btnAddInsuranceProducts" class="btn btn-primary Edit-R" type="button" value="添加保险产品" onclick="showProductLayer()"> <span class="zbjf-desc">可添加一个基础产品或者多个卡产品</span>
            <div class="table-responsive dataTables_wrapper">
                @Html.Hidden("hdntr")
                <table id="sellersList" class="table table-striped table-bordered table-hover">
                    <thead>
                        <tr>
                            <th width="20">序号</th>
                            <th width="80">类型</th>
                            <th width="80">保险产品名称</th>
                            <th width="100">是否启用</th>
                            <th width="100">创建时间</th>
                            <th width="100">操作</th>
                        </tr>
                    </thead>
                    <tbody id="tbodySellerInsuranceProductMappings">
                        @{
    if (Model.SellerInsuranceProductMappings.Any())
    {
        for (int i = 0; i < Model.SellerInsuranceProductMappings.Count(); i++)
        {
            var SellerInsuranceProductMappings = Model.SellerInsuranceProductMappings.ToList();
            var item = SellerInsuranceProductMappings[i];
            if (item.InsuranceProductId.HasValue)
            {
                var baseProduct = ServiceFactory.InsuranceProductsServiceInstance.LoadByID(item.InsuranceProductId.Value);
                <tr>
                    <td>
                        @(i + 1)
                        @Html.HiddenFor(m => SellerInsuranceProductMappings[i].ID)
                        @Html.HiddenFor(m => SellerInsuranceProductMappings[i].SellerInsuranceProductId)
                        @Html.HiddenFor(m => SellerInsuranceProductMappings[i].InsuranceProductId)
                    <td>基础产品</td>
                    <td>@baseProduct.ProductName</td>
                    <td>@(baseProduct.IsAvailable ? "是" : "否")</td>
                    <td>@baseProduct.CreateTime</td>
                    <td><a class='Edit-R' onclick='trRemove(this)'><i class='icon-remove'></i></a></td>
                </tr>
            }
            else if (item.InsuranceProductPackageID.HasValue)
            {
                var baseProduct = ServiceFactory.InsuranceProductPackageServiceInstance.LoadByID(item.InsuranceProductPackageID.Value);
                <tr>
                    <td>
                        @(i + 1)
                        @Html.HiddenFor(m => SellerInsuranceProductMappings[i].ID)
                        @Html.HiddenFor(m => SellerInsuranceProductMappings[i].SellerInsuranceProductId)
                        @Html.HiddenFor(m => SellerInsuranceProductMappings[i].InsuranceProductPackageID)
                    </td>
                    <td>保险卡</td>
                    <td>@baseProduct.ProductPackageName</td>
                    <td>@(baseProduct.IsAvailable ? "是" : "否")</td>
                    <td>@baseProduct.LastModifyTime</td>
                    <td><a class='Edit-R' onclick='trRemove(this)'><i class='icon-remove'></i></a></td>
                </tr>
            }
        }
    }
                        }
                    </tbody>
                </table>
            </div>
        </div>
        <div class="tab-pane  fade in active" id="li1">
            @Html.Action("ProductTagsImages", "SellerInsuranceProducts", new { id = id })
        </div>
        <div class="form-actions" style="text-align: center; ">
            <input id="btnAuditSave" class="btn btn-primary Edit-R" type="submit" value="保存">
            <input id="btnAuditColse" class="btn btn-primary Edit-R" style="width: 60px;" value="放弃创建" onclick="parent.layer.closeAll()">
        </div>
    </div>
}
@section scripts{
    <script src="~/Scripts/uploadAdapter/jquery.loadscript.js"></script>
    <script src="~/Scripts/uploadAdapter/jquery.uploadAdapter.js"></script>
    <script type="text/javascript">
        //实例化编辑器
        var umIntro = UM.getEditor('myEditor');
        window.onload = (function() {
            if (@id > 0) {
                umIntro.setContent($("#Intro").val()); //赋值给UEditor
            }
            $("#ProductName").blur(function() {
                if (isExistSellerProduct(this.value, $("#ID").val())) {
                    layer.alert("产品名称已存在，请修改");
                }
            });
        });

        //选中客户后设置值,清空选中的配件
        function setSelectInsuranceProduct(items, isCardProduct) {
            var tbodySellerInsuranceProductMappings = $("#tbodySellerInsuranceProductMappings").children("tr");
            var insuranceProductIdArray = [];
            var insuranceProductPackageIDArray = [];
            if (tbodySellerInsuranceProductMappings.length > 0) {//非卡产品只能添加一个
                tbodySellerInsuranceProductMappings.each(function() {
                    if ($(this).find("input[type=hidden][id*='InsuranceProductId']").length > 0) {
                        $(this).find("input[type=hidden][id*='InsuranceProductId']").each(function() {
                            insuranceProductIdArray.push(this.value);
                        });
                    }
                    if ($(this).find("input[type=hidden][id*='InsuranceProductPackageID']").length > 0) {
                        $(this).find("input[type=hidden][id*='InsuranceProductPackageID']").each(function() {
                            insuranceProductPackageIDArray.push(this.value);
                        });
                    }
                });
                tbodySellerInsuranceProductMappings.each(function() {
                    if (!isCardProduct) //如果添加基础产品，则全部移除
                    {
                        $(this).remove();
                    }
                    else if (insuranceProductIdArray.length>0) //现在添加的是卡产品,有基础产品，则移除
                    {
                        $(this).remove();
                    }
                });
            }
            var typeName = isCardProduct ? "保险卡" : "基础产品";
            var html = "";
            var addedLength = tbodySellerInsuranceProductMappings.length;//已添加的项的长度
            var removeItemCount = 0;//一共移除了几项（重复的项数）
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                var name = isCardProduct ? item.ProductPackageName : item.ProductName;
                if (insuranceProductIdArray.length > 0||!isCardProduct) {
                    addedLength = 0;//会全部清空
                }
                if (isCardProduct) { //不要添加重复的保险卡，后台也去除重复
                    if (insuranceProductPackageIDArray.indexOf(item.ID.toString()) > -1) {
                        removeItemCount++;
                        continue;
                    }
                }
                var index = addedLength + i-removeItemCount;
                html += "<tr><td>"+(index + 1);
                html += "<input type='hidden' id='SellerInsuranceProductMappings_"+(index)+"__"+(isCardProduct?"InsuranceProductPackageID":"InsuranceProductId")+"' name='SellerInsuranceProductMappings["+index+"]."+(isCardProduct?"InsuranceProductPackageID":"InsuranceProductId")+"' value='" + item.ID + "'/></td>";
                html += "<td>" + typeName + "</td>";
                html += "<td>" + name + "</td>";
                html += "<td>" + (item.IsAvailable ? "是" : "否") + "</td>";
                html += "<td>" + item.CreateTime + "</td>";
                html += "<td><a class='Edit-R' target='_blank' onclick='trRemove(this)'><i class='icon-remove'></i></a></td></tr>";
            }
            $("#tbodySellerInsuranceProductMappings").append(html);
        }

        function trRemove(obj) {
            var index = layer.confirm("是否移除？",
            { btn: ["确定", "取消"] }, function(index) {
                $(obj).parents("tr").remove();
                layer.close(index);
            }, function(index) {
                layer.close(index);
            });
        }


        $("#mvcForm").submit(function() {
            if ($(this).valid()) {
                if (isExistSellerProduct($("#ProductName").val(), $("#ID").val())) {
                    layer.alert("商户保险产品名称已存在，请修改名称！");
                    return false;
                }
                if ($("#tbodySellerInsuranceProductMappings").children("tr").length < 1) {
                    layer.alert("请至少配置一个保险产品");
                    return false;
                }
                if ($("[name='SellerInsuranceProductImages']").length < 1) {
                    layer.alert("请至少上传一张图片");
                    return false;
                }

                $("#Intro").val(umIntro.getContent());
                return true;
            }
            return false;
        });
        function isExistSellerProduct(sellerInsuranceProductName,id) {
            var result = false;
            $.ajax({
                url: "/SellerInsuranceProducts/IsExistSellerProduct?sellerInsuranceProductName=" + sellerInsuranceProductName + "&id=" + id,
                async: false,
                success: function(data) {
                    result = data=="True";
                }
            });
            return result;
        }

        function showProductLayer() {
            layer.open({
                type: 2,
                title: '请选择保险产品',
                shadeClose: true,
                shade: 0.8,
                area: ['820px', '75%'],
                content: '/SellerInsuranceProducts/AddInsuranceProducts'
            });
        }

    </script>
}